angular.module('camera', [])
    .factory('camera', [
        '$ionicActionSheet', '$cordovaCamera', '$q', 'httpService', 'loading', 'ENV', '$cordovaFileTransfer',
        function($ionicActionSheet, $cordovaCamera, $q, httpService, loading, ENV, $cordovaFileTransfer) {
            var getPicture, options, showAction;
            options = {
                quality: 100,
                allowEdit: false,
                targetWidth: 666,
                targetHeight: 666,
                saveToPhotoAlbum: false
            };
            getPicture = function(opt) {
                var q;
                q = $q.defer();
                if (opt === 0) {
                    options.sourceType = Camera.PictureSourceType.CAMERA;
                } else {
                    options.sourceType = Camera.PictureSourceType.PHOTOLIBRARY;
                }
                options.destinationType = Camera.DestinationType.FILE_URI;
                options.encodingType = Camera.EncodingType.JPEG;
                options.popoverOptions = CameraPopoverOptions;
                document.addEventListener('deviceready', (function() {
                    $cordovaCamera.getPicture(options).then((function(imageUrl) {
                        q.resolve(imageUrl);
                    }), function(err) {
                        q.reject(err);
                    });
                }), false);
                return q.promise;
            };
            showAction = function(opt) {
                var hideSheet, q;
                opt = opt || 1;
                q = $q.defer();
                cordova.plugins.Keyboard.close();
                hideSheet = $ionicActionSheet.show({
                    buttons: [{
                        text: '相机'
                    }, {
                        text: '图库'
                    }],
                    titleText: '图片来源',
                    cancelText: '取消',
                    cancel: function() {},
                    buttonClicked: function(index) {
                        hideSheet();
                        getPicture(index).then(function(fileURL) {
                            // q.resolve(res);
                            if (opt == 'fileURL') {
                                q.resolve(fileURL);
                            } else {
                                httpService.query('upload/uploadToken').then(function(res) {
                                    var date, fail, ft, key, options, params, random_int, win;
                                    if (res.code === 200) {
                                        win = function(r) {
                                            q.resolve(res.data.qndomain + JSON.parse(r.response).key);
                                        };
                                        fail = function(error) {
                                            q.reject(JSON.stringify(error));
                                        };
                                        options = new FileUploadOptions();
                                        options.fileKey = 'file';
                                        options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
                                        date = function() {
                                            var date_str;
                                            date_str = '';
                                            date = new Date();
                                            date_str += date.getFullYear();
                                            date_str += date.getMonth() + 1;
                                            date_str += date.getDate();
                                            date_str += date.getHours();
                                            date_str += date.getMinutes();
                                            date_str += date.getSeconds();
                                            return date_str;
                                        };
                                        random_int = parseInt(Math.random() * 1000000);
                                        key = 'usr_app_' + ENV.appId + '_msgimg_' + date() + random_int;
                                        params = {
                                            key: key,
                                            token: res.data.upToken,
                                            x: {
                                                variable: random_int
                                            }
                                        };
                                        options.params = params;
                                        ft = new FileTransfer();
                                        ft.upload(fileURL, 'http://upload.qiniu.com/', win, fail, options);
                                    } else {
                                        loading.prompt('网络异常!');
                                    }
                                });
                            }
                        });
                    }
                });
                return q.promise;
            };
            return {
                getPicture: showAction
            };
        }
    ]);
